;(function () {
    /**
     * jquery全局插件
     */
    $.fn.extend({
        wrapForm: function () {
            var currentObj = $(this);
            if (currentObj.is("form")) {//this是表单id或class
                return currentObj;
            } else {//针对表单没有被包裹form标签，此时this是包裹的div的id或class
                return currentObj.parent().is("form") ? currentObj.parent() : currentObj.wrap("<form></form>").parent();
            }
        },
        serializeForm: function () {//序列化表单成json对象
            return $(this).wrapForm().serializeJSON();
        },
        resetOnFrom: function () {
            var items = $(this).serializeForm();
            $.each(items, function (key, value) {//针对easyui的表单清空
                var selector = $("input[name^=" + key + "]"),
                    selectorEasyUI_Date = $("input[comboname^=" + key + "]"),
                    selectorEasyUI_Select = $("select[comboname^=" + key + "]");
                selectorEasyUI_Select.combobox("select", 0);
                selectorEasyUI_Date.combo("setText", "").combo("setValue", "");
                selector.val("");
            });
        },
        httpUtil_Post: function (url, successCallback) {//此时的选择器是你数据块所在的上层div的class或id
            $.httpUtil_POST(url, $(this).serializeForm(), successCallback);
        },
        httpUtil_Get: function (url, successCallback) {//此时的选择器是你数据块所在的上层div的class或id
            $.httpUtil_GET(url, $(this).serializeForm(), successCallback);
        },
        checkNumber: function () {
            var cnt = 0, current = $(this);
            var numbers = $.makeArray($("input[checkNumber]"));
            $.each(numbers, function (i) {
                var obj = $(numbers[i]);
                if (!$.checkCore(obj.val())) {
                    cnt++;
                    obj.tips({
                        side: 3,
                        msg: '请输入正整数!',
                        bg: '#AE81FF',
                        time: 1
                    });
                }
            });
            if (cnt > 0) return;
            $(current).submit();
        },
        getSUM: function (url) {
            var current = $(this);
            $.ajax({
                type: 'POST',
                url: url,
                data: current.serialize(),
                success: function (data) {
                    $("#getSUM").html(data);
                }
            })
        },
		getMobileAddr:function (index,mobile){
        	var current = $(this);
			$.get("call/tableIndex"+ index + "/getMobileAddr/" + mobile, function(data){
				if(data){
					current.parent().html(data);
				}
			});
		}
    });

    /**
     * jquery的全局方法
     */
    $.extend({
        /**
         * ajax Post
         * @param url 请求地址
         * @param data 参数
         * @param successCallback 请求成功的回调函数
         */
        httpUtil_POST: function (url, data, successCallback) {
            var condition = (arguments.length == 2 && arguments[1] instanceof Function);
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                data: !condition ? arguments[1] : (arguments.length == 3 ? arguments[1] : {})
            }).then(
                condition ? arguments[1] : (arguments.length == 3 ? arguments[2] : function () {
                }),//success function
                function (response) {//fail function
                    layer.msg(response.status + "<br/>" + response.statusText + "!");
                }
            );
        },
        /**
         * ajax Get
         * @param url 请求地址
         * @param data 参数
         * @param successCallback 请求成功的回调函数
         */
        httpUtil_GET: function (url, data, successCallback) {//此时的选择器是你数据块所在的上层div的class或id
            var condition = (arguments.length == 2 && arguments[1] instanceof Function);
            $.ajax({
                url: url,
                type: "get",
                dataType: "json",
                data: !condition ? arguments[1] : (arguments.length == 3 ? arguments[1] : {})
            }).then(
                condition ? arguments[1] : (arguments.length == 3 ? arguments[2] : function () {
                }),//success function
                function (response) {//fail function
                    layer.msg(response.status + "<br/>" + response.statusText + "!");
                }
            );
        },
        /**
         * 掩码核心
         * @param value 要掩码字符串
         * @param noMaskSuffix 该字符串保留后几位不掩码
         * @param maskLength 掩码长度
         */
        coverCore: function (value, noMaskSuffix, maskLength) {
            var format = '*', newStr = "", len = value.length;
            var noMaskPreffix = len - noMaskSuffix - maskLength;
            for (var i = 0; i < len; i++) {
                if (i < noMaskPreffix) {
                    newStr = newStr.concat(value[i]);
                } else if (i >= noMaskPreffix + noMaskSuffix) {
                    newStr = newStr.concat(value[i]);
                } else {
                    newStr = newStr.concat(format);
                }
            }
            return newStr;
        },
        /**
         * 手机掩码
         * @param value
         * @returns {*}
         * @constructor
         */
        MOBILE: function (value) {
            if (value.length != 11) {
                alert("手机号码格式不对");
                return;
            }
            if($.hasRoleOnCover()){
                return value;
            }
            return $.coverCore(value,4,4);
        },
        checkCore: function (val) {
            var reg = /^[0-9]*[0-9][0-9]*$/;
            if (reg.test(val) || val == "") {
                return true;
            } else {
                return false;
            }
        },
        hasRoleOnCover:function(){
            var admin  = $("[name='ADMIN']").val();
            var cszz  = $("[name='CSZZ']").val();
            var csjl  = $("[name='CSJL']").val();
            var role_ID  = $("[name='currentRoleID']").val();
            if(role_ID == csjl){
                //催收经理
                return  true;
            }else if(role_ID == admin){
                //admin
                return  true;
            }
            return false;

        },
        /**
         * 解析json
         * @param data json数据
         */
        dictionary: function (data) {
            var Core = function () {
                this.data = $.parseJSON(data);
            };
            Core.prototype = {
                gets: function () {
                    return this.data;
                },
                getByKey: function (key) {
                    return this.gets()[key];
                }
            };
            return new Core();
        },
        /**
         * 锁定菜单
         * @param menu
         * @param message
         */
        lockMenu:function(menu){
            var allDoc = $(parent.parent.parent.window.document);
            allDoc.find("a[target='mainFrame']:contains('" + menu + "')")
                .css({"pointer-events":"none"}).parent()
                .on('click',function(){
                    allDoc.find("#mainFrame").trigger("click");
                });
            $(parent.parent.window.document).find(".tab_close").parent().prev(":contains('" + menu + "')")
                .next().children().wrap("<label style='visibility:hidden;'></label>");
            $.layerClose(false);
        },
        /**
         * 解锁菜单
         * @param menu
         */
        unLockMenu:function(menu){
            var allDoc = $(parent.parent.parent.window.document);
            allDoc
                .find("a[target='mainFrame']:contains('" + menu + "')")
                .css({"pointer-events":""}).parent().off("click");
			$(parent.parent.window.document).find(".tab_close").parent().parent().prev(":contains('" + menu + "')")
                .next().children().children().unwrap();
			$.layerClose(true);
        },
		/**
		 * 获取当前tab 名称
		 * @returns {*|jQuery}
		 */
		getCurrentTabName:function(){
			var iid = "#" + $.getCurrentIframeId().split("_")[1];
			return $(parent.parent.window.document).find(iid + " td:eq(1)").html();
		},
		getCurrentIframeId:function(){
			return $(parent).get(0)["frameElement"]["id"];
		},
		layerClose:function(flag){
			var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
			parent.layer.closeButton(index,flag);
		},
		/**
		 * 导出excel
		 * @param url
		 */
		getExcel: function (url) {
			var key = $.getKey();
			location.href = url + key;
			setTimeout(function () {
				$.get("excel/isOutExcelSuccess?"+key, function (r) {
					if (r == true) return;
					layer.open({
						title: "正在导出，请稍等.....",
						type: 1,
						area: ['255px'], //宽高
						closeBtn: 0, //不显示关闭按钮
						content: setCanvasBar(key),//组装页面
					});
				});
			}, 777);
		},
		getKey: function () {
			var r1 = (new Date()).getTime();
			var r2 = (Math.random()).toString().split(".")[1];
			return "&key=excelFlag" + r1 + r2;
		},
        tiaozhuan:function (obj,callLoanNid,userId,repaymentId,name,flag){
            $(obj).css("color","red");
            // siMenu(callLoanNid,callLoanNid,name,'cuijimanage/toDescPage.do?callLoanNid='+callLoanNid+'&userId='+userId+'&repaymentId='+repaymentId)
            var index = layer.open({
                title:name+'详情',
                type: 2,
                content: 'cuijimanage/toDescPage.do?callLoanNid='+callLoanNid+'&userId='+userId+'&repaymentId='+repaymentId+'&flag='+flag,
                area: ['320px', '195px'],
                maxmin: false
            });
            layer.full(index);
			layer.iframeAuto(index);
        },
        tiaozhuanWai:function (obj,callLoanNid,userId,repaymentId,name,flag){
            $(obj).css("color","red");
            // siMenu(callLoanNid,callLoanNid,name,'cuijimanage/toDescPage.do?callLoanNid='+callLoanNid+'&userId='+userId+'&repaymentId='+repaymentId)
            var index = layer.open({
                title:name+'详情',
                type: 2,
                content: 'assign/toAssignOutDescPage.do?callLoanNid='+callLoanNid+'&userId='+userId+'&repaymentId='+repaymentId+'&flag='+flag,
                area: ['320px', '195px'],
                maxmin: false
            });
            layer.full(index);
			layer.iframeAuto(index);
        }
    });

    window.message = function (msg, option, end) {
        layer.msg(msg, option, end);
    }

    window.alert = function (msg) {
        layer.msg(msg);
    }

    window.log = function (key, value) {
        console.log(key + ":");
        console.log(value);
    }

    window.consoles = function (value) {
        console.log(value);
    }

	var setCanvasBar = function (key) {
		var html = [
				'<style type="text/css">',
				'#c{',
				'margin: 0 auto;',
				'display: block;',
				'}',
				'</style>',
				'<script src="static/js/excelBar.js"></script>',
				'<script language = "javascript">',
				'var time1,time2;',
				'function setSB(v, el) {',
				'var rr = parseInt($(el).val());',
				'$("#r").val(v);',
				'}',
				'function fakeProgress(v, el) {',
				'isSuccess(v,el);',
				'}',
				'function isSuccess(v,el) {',
				'$.get("excel/isOutExcelSuccess?'+key+'",function(r){',
				'if(r != true){',
				'var xy = ~~(Math.random()*4+83);',
				'if (v > xy){v=xy;layer.load(2);}else{setSB(v, el);}',
				'time1 = setTimeout(function(){isSuccess((++v),el);},900);',
				'}else{',
				'clearTimeout(time1);',
				'time2 = setInterval(function(){',
				'if (v > 100){clearInterval(time2);$.get("excel/removeExcelFlag?'+key+'");layer.closeAll();}',
				'setSB((v+=35), el);',
				'},222);',
				'}',
				'});',
				'}',
				'$(function () {',
				'fakeProgress(0, "#r");',
				'});',
				'</script>',
				'<canvas id="c"></canvas>',
				'<input type="hidden" id="r" value="0">'
			]
		;
		return html.join("\r\n");
	}
	
	window.ba = function(str) {
		str = str.replace(/\\/g, "%");
		return unescape(str);
	}
	
	window.ab = function(str){
		var strArr = str.split(",");
		var strArray = [];
		for(var i = 0;i < strArr.length;i++){
			strArray.push(("00" + strArr[i]).slice(-4));
		}
		return "\\u" + strArray.join("\\u");
	}
	
	window.abc = function(str){
		var strArr = [];
		for(var i = 0;i < str.length;i++){
			strArr.push(str.charCodeAt(i).toString(16));
		}
		return strArr.join(",");
	}
})();